import React, {useRef, useState} from 'react';
import axios from "axios";
import {
    Link,
    useNavigate
} from "react-router-dom"
export default function Home(props) {
    const navigate = useNavigate();
    const searchRef = useRef();
    const [items,setItems] = useState(localStorage.getItem("items")?JSON.parse(localStorage.getItem("items")):[]);
    const [isLoading,setIsLoading] = useState(false);
    let timer = null;
    const searchUserList = function(){
        if(timer) clearTimeout(timer);
        timer = setTimeout(function (){
            const q = searchRef.current.value.trim();
            if(q.length===0){
                setItems([])
                return;
            }
            setIsLoading(true);
            axios.get("https://api.github.com/search/users",{
                params:{
                    q,
                    sort:"stars"
                }
            }).then(value=>{
                console.log(value.data);
                setItems(value.data.items);
                localStorage.setItem("items",JSON.stringify(value.data.items));
                localStorage.setItem("q",q);
                setIsLoading(false);
            })
        },500)
    }


    // const searchUserList = function(e){
    //     e.preventDefault();
    //     const q = searchRef.current.value.trim();
    //     if(q.length===0){
    //         alert("请输入搜索的关键词");
    //         return;
    //     }
    //     axios.get("https://api.github.com/search/users",{
    //         params:{
    //             q,
    //             sort:"stars"
    //         }
    //     }).then(value=>{
    //         console.log(value.data);
    //         setItems(value.data.items);
    //     })
    // }
    return (
        <div>
            <form>
                <input defaultValue={localStorage.q} onInput={searchUserList} ref={searchRef} type="text"/>
            </form>
            {
                isLoading?<h3>正在加载中……</h3>:items.map(item=>(
                    <p key={item.id}>
                        <Link to={"/details/"+item.login+".html"}>{item.login}</Link>
                    </p>
                ))
            }
        </div>
    );
}
